<template>
  <div class="app-container">
    <el-input v-model="message" size="small" placeholder="请输入消息" maxlength="64" show-word-limit clearable />
    <div slot="footer" class="dialog-footer" style="margin-top:10px">
      <el-button :disabled="socketOpen" size="small" type="primary" @click="initWebSocket()">建立连接</el-button>
      <el-button :disabled="!socketOpen" size="small" type="success" @click="webSocketSend(message)">发送信息</el-button>
      <el-button :disabled="!socketOpen" size="small" type="danger" @click="webSocketClose()">关闭连接</el-button>
    </div>
  </div>
</template>

<script>

export default {
  props: {},
  data() {
    return {
      websock: null,
      message: '',
      socketOpen: false
    }
  },
  // created() {
  //   this.initWebSocket()
  // },
  methods: {
    initWebSocket() {
      if (this.websock) {
        this.$message.error('WebSocket已经建立连接')
        return
      }
      // process.env.VUE_APP_WS_API +
      // /webSocket/{api}/{uid} => api: 接口, uid: 用户ID
      const wsUri = 'ws://localhost:90/jjcm/webSocket/deploy/aabb'
      this.websock = new WebSocket(wsUri)
      this.websock.onopen = this.webSocketOnOpen
      this.websock.onclose = this.webSocketOnClose
      this.websock.onerror = this.webSocketOnError
      this.websock.onmessage = this.webSocketOnMessage
    },
    webSocketOnOpen(e) {
      this.socketOpen = true
      console.log('webSocketOnOpen', e)
      this.$message.success('WebSocket已经建立连接')
    },
    webSocketOnClose(e) {
      this.socketOpen = false
      console.log('webSocketOnClose', e)
      this.$message.success('WebSocket已经关闭连接')
    },
    webSocketOnError(e) {
      this.socketOpen = false
      console.log('webSocketOnError', e)
      this.$message.success('WebSocket连接发生错误')
    },
    webSocketOnMessage(e) {
      console.log('webSocketOnMessage', e)
      this.$message.success('接收到消息内容:' + e.data)
    },
    webSocketClose() {
      console.log('关闭连接')
      if (this.websock) {
        this.websock.close()
        this.websock = null
        this.socketOpen = false
      } else {
        this.$message.error('WebSocket还未建立连接')
      }
    },
    webSocketSend(message) {
      console.log('发送消息', message)
      if (!this.websock || !this.socketOpen) {
        this.$message.info('WebSocket还未建立连接')
        return
      }
      if (!message || message.length <= 0) {
        this.$message.info('请输入信息')
        return
      }
      this.websock.send(message)
    }
  }
}
</script>

<style scoped>
</style>
